package com.tj.collection.db.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.fqgj.common.api.Response;
import com.fqgj.common.utils.StringUtils;
import com.fqgj.exception.common.ApplicationException;
import com.fqgj.msg.utils.Paged;
import com.kly.user.dto.UserInfoDto;
import com.kly.user.dto.user.*;
import com.kly.user.service.BehaviorService;
import com.kly.user.service.UserService;
import com.tj.collection.controller.user.request.UserBehaviorRequest;
import com.tj.collection.controller.user.request.UserListRequest;
import com.tj.collection.controller.user.response.*;
import com.tj.collection.db.dao.ChannelDictDao;
import com.tj.collection.db.entity.ChannelDictEntity;
import com.tj.collection.db.service.UserManageService;
import com.tj.collection.enums.MemberStatusEnum;
import com.tj.collection.utils.DateUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.util.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: UserServiceImpl
 * @description: 用户管理service实现类
 * @author: yuwn
 * @create: 2023-11-21 20:11
 */
@Service("userManageService")
@Slf4j
public class UserManageServiceImpl implements UserManageService {


    @NacosValue(value = "${user.photoPrefix}", autoRefreshed = true)
    private String userPhotoPrefix;

    @Resource
    UserService userService;

    @Resource
    BehaviorService behaviorService;

    @Autowired
    private ChannelDictDao channelDictDao;


    @Override
    public Paged<List<UserResponse>> getUserList(UserListRequest requestDTO) {



        UserQueryDto userQueryDTO = new UserQueryDto();
        userQueryDTO.setUserCode(requestDTO.getUserCode());
        userQueryDTO.setEmail(requestDTO.getEmail());
        userQueryDTO.setNickName(requestDTO.getNickName());
        if(StringUtils.isNotEmpty(requestDTO.getChannel()) ){
            userQueryDTO.setChannel(requestDTO.getChannel().toLowerCase());
        }
        userQueryDTO.setPhone(requestDTO.getPhone());
        userQueryDTO.setPageSize(requestDTO.getPageSize());
        if(requestDTO.getCurrent() != null){
            userQueryDTO.setCurrentPage(requestDTO.getCurrent());
        }else{
            userQueryDTO.setCurrentPage(requestDTO.getCurrentPage());
        }




        Response<UserInfoPageDto> response = userService.getUserList(userQueryDTO);

        if(response.isSuccess()){
            if(response.getData().getUserInfoDtos() == null || response.getData().getUserInfoDtos().isEmpty()){
                return new Paged<>();
            }
            List<UserResponse> userResponseDTOS = response.getData().getUserInfoDtos().parallelStream().map(x->{
                UserResponse userResponseDTO = new UserResponse();
                BeanUtil.copyProperties(x,userResponseDTO);
                MemberStatusEnum memberStatusEnum = MemberStatusEnum.getEnumByCode(x.getStatus());
                if(memberStatusEnum != null){
                    userResponseDTO.setMemberStatus(memberStatusEnum.getDescription());
                }
                return userResponseDTO;
            }).collect(Collectors.toList());

            return new Paged<>(response.getData().getTotalCount(),requestDTO.getPageSize(),requestDTO.getCurrentPage(),userResponseDTOS);
        }


        return new Paged<>();
    }

    @Override
    public Paged<List<UserBehaviorResponse>> getUserBehaviorList(UserBehaviorRequest requestDTO) {
        BehaviorQueryDto userBehaviorQueryDTO = new BehaviorQueryDto();
        String[] format = new String[]{"dd-MMM-yy HH:mm:ss"};
        Date startTime = getDate(requestDTO.getStartDate()+" 00:00:00");
        userBehaviorQueryDTO.setStartTime(startTime);
        Date endTime = getDate(requestDTO.getEndDate()+" 23:59:59");
        userBehaviorQueryDTO.setEndTime(endTime);
        userBehaviorQueryDTO.setCurrentPage(requestDTO.getCurrentPage());
        userBehaviorQueryDTO.setPageSize(requestDTO.getPageSize());
        userBehaviorQueryDTO.setUserCode(requestDTO.getUserCode());


        Response<BehaviorResponsePageDto> response = behaviorService.getBehaviorList(userBehaviorQueryDTO);

        if(response.isSuccess()){
            if(response.getData() == null || response.getData().getBehaviorResponseDtos().isEmpty()){
                return new Paged<>();
            }

            Paged<List<UserBehaviorResponse>> paged = new Paged<>();
            List<UserBehaviorResponse> behaviorResponseDtos = response.getData().getBehaviorResponseDtos().parallelStream().map(x->{
                UserBehaviorResponse userBehaviorResponseDTO = new UserBehaviorResponse();
                BeanUtil.copyProperties(x,userBehaviorResponseDTO);
                userBehaviorResponseDTO.setOperationEvent(x.getActionName());
                userBehaviorResponseDTO.setPageSource(x.getSourcePage());
                userBehaviorResponseDTO.setOperationTime(x.getOperateTime());
                return userBehaviorResponseDTO;
            }).collect(Collectors.toList());

            paged.setData(behaviorResponseDtos);
            paged.setTotalCount(response.getData().getTotalCount());

            return paged;
        }
        return new Paged<>();
    }

    @Override
    public UserInfoResponse getUserDescriptionByCode(UserListRequest requestDTO) {

        Response<UserInfoDto> response = userService.getAllUserByUserCode(requestDTO.getUserCode());

        if(response.isSuccess()){
            if(response.getData() == null){
                return null;
            }
            UserInfoDto userInfoDto = response.getData();

            UserInfoResponse userInfoResponseDTO = new UserInfoResponse();
            BeanUtil.copyProperties(userInfoDto,userInfoResponseDTO);

            userInfoResponseDTO.setTurnOns(userInfoDto.getTurnOnsList());
            userInfoResponseDTO.setWhyYouHere(userInfoDto.getPurpose());

            PhotosInfo photosInfoDTO = new PhotosInfo();
            photosInfoDTO.setAvator(userPhotoPrefix+userInfoDto.getAvatarUrl());
            if(userInfoDto.getImages() !=null &&userInfoDto.getImages().size()>0){
                List<String> images = userInfoDto.getImages().stream().map(x->{
                    return userPhotoPrefix+x;
                }).collect(Collectors.toList());
                photosInfoDTO.setPhotos(images);
            }


            userInfoResponseDTO.setPhotosInfoDTOS(photosInfoDTO);

            if(userInfoDto.getPrivateAlbumPhotos() !=null &&userInfoDto.getPrivateAlbumPhotos().size()>0){
                List<String> images = userInfoDto.getPrivateAlbumPhotos().stream().map(x->{
                    return userPhotoPrefix+x;
                }).collect(Collectors.toList());
                userInfoResponseDTO.setAlbumsInfoResponseDTOS(images);
            }


            return userInfoResponseDTO;
        }else{
            throw new ApplicationException(response.getMsg());
        }

    }

    @Override
    public List<ChannelDictResp> getChannelList() {

        Map<String,Object> params = new HashMap<>();
        params.put("deleted",false);
        List<ChannelDictEntity> channelDictEntities = channelDictDao.selectByParams(params);


        return channelDictEntities.parallelStream().map(x->{
            ChannelDictResp channelDictResp = new ChannelDictResp();
            channelDictResp.setChannelCode(x.getChannelCode());
            return channelDictResp;
        }).collect(Collectors.toList());
    }

    private Date getDate(String date){
        try {
            return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }
    }

}
